<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="changeFile"
      :before-upload="beforeUpload"
      :http-request="upload"
      :limit="1"
      :class="{disabled: fileList.length === 1}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showProgress" :percentage="percentage" style="width: 180px" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDXv51lJcgU3NSHsELCn8DKBpDOK0ax4wh',
  SecretKey: 'ZswkIgpiNoysWu2tWt1wd4FBrGPIvHND'
})
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      currentId: null,
      percentage: 0,
      showProgress: false
    }
  },
  methods: {
    handleRemove(file, fileList) {
    //   console.log(file, fileList)
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    //   console.log(file)
    },
    changeFile(file, fileList) {
      this.fileList = fileList.map(item => item)
    },
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      const maxSize = 5 * 1024 * 1024
      if (!types.some(item => item === file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      if (file.size > maxSize) {
        this.$message.error('图片大小最大不能超过5M')
        return false
      }
      this.currentId = file.uid
      this.showProgress = true
      return true
    },
    upload(params) {
      // console.log(params)
      if (params.file) {
        cos.putObject({
          Bucket: 'test-1313944623', /* 填入您自己的存储桶，必须字段 */
          Region: 'ap-chongqing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
          Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
          StorageClass: 'STANDARD',
          Body: params.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percentage = progressData.percent * 100
          }
        }, (err, data) => {
          // console.log(err || data)
          if (!err && data.statusCode === 200) {
            this.fileList = this.fileList.map(item => {
              if (this.currentId === item.uid) {
                console.log(data.Location)
                return { url: 'http://' + data.Location, upload: true }
              }
              return item
            })
          }
          setTimeout(() => {
            this.showProgress = false
            this.percentage = 0
            console.log(this.fileList)
          }, 1000)
        })
      }
    }
  }
}
</script>

<style>
 .disabled .el-upload--picture-card{
    display: none;
 }
</style>
